﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using BookExchange.Business;
using BookExchange.CustomClass.Base;
using BookExchange.Utility;
using BookExchange.ViewModel;
using BookExchange.Configuration;

namespace BookExchange
{
    public partial class Login : BasePage
    {
        MemberBusiness memberBus;
        public Login()
            : base()
        {
            memberBus = new MemberBusiness();
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {

            }
        }

        protected void btnLogin_Click(object sender, EventArgs e)
        {
            //Get username & password & Remember me
            var email = txtEmail.Text;
            var pw = txtPassword.Text;
            bool rememberMe = chkRememberme.Checked;
            var pageReturn = string.Empty;

            //Do login
            bool loginSuccessfully = LoginWithUser(email, pw, rememberMe);            

            //Trả người dùng về trang web cũ            
            var returnPage = Request.QueryString["ReturnUrl"];
            returnPage = string.IsNullOrEmpty(returnPage) ? "default.aspx" :  returnPage;
            if (string.IsNullOrEmpty(returnPage))
            {
                RedirectToHomepage();
            }
            else
            {
                Response.Redirect(returnPage);
            }
        }

        public bool LoginWithUser(string email, string password, bool rememberMe)
        {
            //validate xem có hợp lệ hay không
            bool result = false;
            var existsMember = memberBus.GetMember(email, password);

            //Nếu tồn tại thì set userID vào sesion rồi 
            if (existsMember != null)
            {
                this.Login(existsMember);
                Session.Timeout = rememberMe ?
                    AppConfiguration.Instance.MaximumSessionTimeout : AppConfiguration.Instance.DefaultSessionTimeout;
                result = true;
            }
            else
            {
                //TODO://set text to errorLabel when member not exists
                result = false;
            }            

            return result;
        }
    }
}